<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use app\admin\model\RouteModel;
use think\Db;
use think\Model;
use tree\Tree;

class #model_name# extends Model
{

    protected $type = [
        'more' => 'array',
    ];

    /**
     * 生成分类 select树形结构
     * @param int $selectId 需要选中的分类 id
     * @param int $currentCid 需要隐藏的分类 id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminCategoryTree($selectId = 0, $currentCid = 0)
    {
        $where = [];
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }
        $categories = $this->order("listorder DESC")->where($where)->select()->toArray();

        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        $newCategories = [];
        foreach ($categories as $item) {
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";

            array_push($newCategories, $item);
        }

        $tree->init($newCategories);
        $str = '
        <option value=\"{$id}\" {$selected}>{$spacer}{$title}</option>';
        $treeStr = $tree->getTree(0, $str);

        return $treeStr;
    }

    /**
     * 分类树形结构
     * @param int $currentIds
     * @param string $tpl
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminCategoryTableTree($currentIds = 0, $tpl = '')
    {
        $where = [];
//        if (!empty($currentCid)) {
//            $where['id'] = ['neq', $currentCid];
//        }
        $categories = $this->order("listorder DESC")->where($where)->select()->toArray();

        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }

        $newCategories = [];
        foreach ($categories as $item) {
            $item['parent_id_node'] = ($item['parent_id']) ? ' class="child-of-node-' . $item['parent_id'] . '"' : '';
            $item['style'] = empty($item['parent_id']) ? '' : 'display:none;';
            $item['status_text'] = empty($item['status']) ? '隐藏' : '显示';
            $item['create_time'] = empty($item['create_time']) ? 0 : date('Y-m-d H:i:s');
            $item['update_time'] = empty($item['update_time']) ? 0 : date('Y-m-d H:i:s');
            $item['checked'] = in_array($item['id'], $currentIds) ? "checked" : "";
            $item['url'] = url("#CONTROLLERNAME#/edit", ["id" => $item['id']]);
            $item['str_action'] = '';

            $item['str_action'] .= '<a href="' . url("#CONTROLLERNAME#/add", ["parent" => $item['id']]) . '">添加子分类</a> &nbsp';
//            if ($item['is_not_addarticle'] == 0) $item['str_action'] .= '<a href="' . url("AdminArticle/add", ["cid" => $item['id']]) . '">添加文章</a> &nbsp';
            if (qbt_is_super_admin() || $item['is_not_edit'] == 0) {
                $item['str_action'] .= '<a href="' . url("#CONTROLLERNAME#/edit", ["id" => $item['id']]) . '">' . lang('EDIT') . '</a> &nbsp';
                if ($item['status']) {
                    $item['str_action'] .= '<a class="js-ajax-dialog-btn" data-msg="您确定隐藏此分类吗"
                           href="' . url('#CONTROLLERNAME#/toggle', ['ids' => $item['id'], 'hide' => 1]) . '">隐藏&nbsp;</a>';
                } else {
                    $item['str_action'] .= '<a class="js-ajax-dialog-btn" data-msg="您确定显示此分类吗"
                           href="' . url('#CONTROLLERNAME#/toggle', ['ids' => $item['id'], 'display' => 1]) . '">显示&nbsp;</a>';
                }
            }
             $item['str_action'] .= '<a class="js-ajax-delete" href="' . url("#CONTROLLERNAME#/delete", ["id" => $item['id']]) . '">' . lang('DELETE') . '</a> ';
            array_push($newCategories, $item);
        }

        $tree->init($newCategories);

        if (empty($tpl)) {
            $tpl = "
<tr id='node-\$id' \$parent_id_node style='\$style' data-parent_id='\$parent_id' data-id='\$id'>
    <td style='padding-left:20px;'><input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x'
                                          name='ids[]' value='\$id' data-parent_id='\$parent_id' data-id='\$id'></td>
    <td><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input-order'></td>
    <td>\$id</td>
    <td>\$spacer<a href='\$url' target='_blank'>\$title</a></td>
    #field_list#
    <td>\$status_text</td>
    <td>\$create_time</td>
    <td>\$update_time</td>
    <td>\$str_action</td>
</tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);

        return $treeStr;
    }

    /**
     * 添加文章分类
     * @param $data
     * @return bool
     */
    public function addCategory($data)
    {
        $result = true;
        self::startTrans();
        try {
            $this->allowField(true)->save($data);
            $id = $this->id;
            if (empty($data['parent_id'])) {

                $this->where(['id' => $id])->update(['path' => '0-' . $id]);
            } else {
                $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
                $this->where(['id' => $id])->update(['path' => "$parentPath-$id"]);

            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            $result = false;
        }

        return $result;
    }

    public function editCategory($data)
    {
        $result = true;

        $id = intval($data['id']);
        $parentId = intval($data['parent_id']);
        $oldCategory = $this->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath-$id";
            }
        }

        if (empty($oldCategory) || empty($newPath)) {
            $result = false;
        } else {

            $data['path'] = $newPath;

            $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

            $children = $this->field('id,path')->where('path', 'like', $oldCategory['path'] . "-%")->select();
            if (!$children->isEmpty()) {
                foreach ($children as $child) {
                    $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
                    $this->where('id', $child['id'])->update(['path' => $childPath], ['id' => $child['id']]);
                }
            }
        }


        return $result;
    }

    public function getCategoryInfo($id)
    {
        return $this->where(['id' => $id])->find();
    }

    public function getCategoryLists($parent_id = 0, $child = 0, $now_level = 0)
    {
        $categorys = $this->where(['parent_id' => $parent_id])->select();
        foreach ($categorys as $k => $v) {

        }
        return $categorys;
    }

    public function getCategoryIds($parent_id)
    {
        $ids = $parent_id;
        $categorys = $this->where(['parent_id' => $parent_id])->select();
        foreach ($categorys as $v) {
            $ids .= ",{$v['id']}";
        }
        return $ids;
    }
}